"""
@file: main.py
@author: lingdubing
@time: 2024/10/31  14:11
@desc: 程序的入口
@character: utf-8
"""

from fastapi import FastAPI, HTTPException
from config import settings
from core import Events, Router
from core.Middleware import LogRequestMiddleware
from tortoise.exceptions import OperationalError, DoesNotExist, IntegrityError, ValidationError
from fastapi.exceptions import RequestValidationError
from core import Exceptions


application = FastAPI(
    debug=settings.APP_DEBUG,
)

# 事件监听
application.add_event_handler("startup", Events.startup(application))
application.add_event_handler("shutdown", Events.stopping(application))

# 异常处理
application.add_exception_handler(HTTPException, Exceptions.http_error_handler)
application.add_exception_handler(RequestValidationError, Exceptions.http422_error_handler)
application.add_exception_handler(DoesNotExist, Exceptions.mysql_does_not_exist)
application.add_exception_handler(IntegrityError, Exceptions.mysql_integrity_error)
application.add_exception_handler(ValidationError, Exceptions.mysql_validation_error)
application.add_exception_handler(OperationalError, Exceptions.mysql_operational_error)

# 中间件挂载

# 日志中间件
application.add_middleware(LogRequestMiddleware)

# 路由挂载
application.include_router(Router.router)

app = application

